 //
//  CurrencyTradeViewController.swift
//  Exchange
//
//  Created by rui on 2018/4/18.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class CurrencyTradeViewController: BaseViewController, SEMenuAdverDelegate {
    private var selectIndex = 0
    
    var redDot: UIView?
    
    lazy var viewModel: TradeMsgViewModel =  {
        let vm = TradeMsgViewModel()
        vm.response = {[weak self](state,isSuccess,errorMsg)in
            if state == ResponseState.trade_trade_unreadMsg  {
               self?.unReadDot()
            }
        }
        return vm
    }()
    
    var addAdverBtn: CustomBtn = {
        return CustomBtn(style: .styleCommon)
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initNavi()
        initUI()
        initData()
    }
    
    func initUI() {
        self.automaticallyAdjustsScrollViewInsets = false
        let buy = BuyViewController()
        let sell = SellViewController()
        self.addChildViewController(buy)
        self.addChildViewController(sell)
        buy.view.frame = self.view.bounds
        buy.view.autoresizingMask = [.flexibleHeight,.flexibleWidth]
        self.view.addSubview(buy.view)
        buy.didMove(toParentViewController: self)
        
        addAdverBtn.photoImageView.image = UIImage(named: "addAdver")
        addAdverBtn.addTarget(self, action: #selector(pushAdver), for: UIControlEvents.touchUpInside)
        self.view.addSubview(addAdverBtn)
        addAdverBtn.photoImageView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        addAdverBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(isiPhoneX() ? -106 : -74)
            make.width.height.equalTo(80)
        }
    }
    
    func initData() {
        NotificationCenter.default.addObserver(self, selector: #selector(loadUnReadMsg), name: NSNotification.Name.Exchange.chatNeedRefresh, object: nil)
    }
    
    lazy var leftBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(showSlider), for: .touchUpInside)
        btn.contentHorizontalAlignment = .left
        btn.frame = CGRect(x: 0, y: 0, width: 100, height: 44)
        btn.titleLabel?.font = UIFont(name: "PingFang-SC-Bold", size: 14)
        btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text1, for: .normal)
        btn.themeSetImage(ThemeManager.ThemeImageKeys.coinRetract, for: .normal)
        btn.setTitle("  ", for: .normal)
        return btn
    }()
    
    func initNavi() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        let s = UISegmentedControl(items: [kText("买入"),kText("卖出")])
        s.addTarget(self, action: #selector(segmentedChange(segmentedControl:)), for: .valueChanged)
        s.width = 150
        s.selectedSegmentIndex = 0
        self.navigationItem.titleView = s
        
        let item1 = UIBarButtonItem(image: #imageLiteral(resourceName: "goto_adver"), style: .plain, target: self, action: #selector(advertisement))
        
        
        let orderView = UIView(frame: CGRect(x: 0, y: 0, width: 22, height: 44))
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(order))
        orderView.addGestureRecognizer(tapGesture)
        
        let icon = UIImageView(image: #imageLiteral(resourceName: "goto_order"))
        icon.themeTintColor = ThemeManager.ThemeColorKeys.text2
        icon.contentMode = .center
        icon.frame = orderView.bounds
        orderView.addSubview(icon)
        
        let red = UIView(frame: CGRect(x: 12, y: 8, width: 10, height: 10))
        redDot = red
        redDot?.isHidden = true
        red.layer.cornerRadius = 5
        red.backgroundColor = UIColor.red
        orderView.addSubview(red)
        
        let item2 = UIBarButtonItem(customView: orderView)
        
        self.navigationItem.rightBarButtonItems = [item2,item1]
        
        
        AppContext.default.getTradeCoins { (models) in
            if let model = models.first {
                self.changeVarity(name: model.coinCode ?? "")
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.loadUnReadMsg()
    }
    
    @objc func loadUnReadMsg() {
        if AppInfo.default.isLogin {
            self.viewModel.loadUnReadMsg()
        }else {
            self.redDot?.isHidden =  true
        }
    }
    
    // MARK: - event
    ///发布广告
    @objc func advertisement() {
        if !AppInfo.default.isLogin {
         let vc = LoginViewController()
         self.navigationController?.pushViewController(vc, animated: true)
            return
        }
        let vc =  AdvertisingListViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK: SEMenuAdverDelegate
    func openAdverment(buyAdsBool: Bool) {
        let controller = AdvertViewController()
        controller.viewModel?.isBuyBool = buyAdsBool
        controller.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(controller, animated: true)
    }
    
    ///订单页面
    @objc func order() {
        dPrint("订单页面")
        self.navigationController?.customCheckLoginPushViewController(animated: true, { () -> UIViewController in
            let vc = TradeOrderCenterViewController()
            return vc
        })
    }
    
    @objc func segmentedChange(segmentedControl: UISegmentedControl) {
        let selectedIndex = segmentedControl.selectedSegmentIndex
        let disappearVC = self.childViewControllers[self.selectIndex]
        let appearVC = self.childViewControllers[selectedIndex]
        disappearVC.willMove(toParentViewController: nil)
        disappearVC.view.removeFromSuperview()
        appearVC.view.frame = self.view.bounds
        appearVC.view.autoresizingMask = [.flexibleHeight,.flexibleWidth]
        self.view.addSubview(appearVC.view)
        appearVC.didMove(toParentViewController: self)
        self.selectIndex = selectedIndex
        self.view.bringSubview(toFront: addAdverBtn)
        dPrint(selectedIndex)
    }
    
    @objc func pushAdver() {
        if !AppInfo.default.isLogin {
            let vc = LoginViewController()
            self.navigationController?.pushViewController(vc, animated: true)
            return
        }
        let view = SEMenuAnimateView()
        view.delegate = self
        view.show()
    }
    @objc func showSlider() {
        let silder = SliderViewController()
        silder.completion = {[weak self](name)in
            self?.changeVarity(name: name)
        }
        silder.modalPresentationStyle = .custom
        silder.transitioningDelegate = self
        self.present(silder, animated: true, completion: nil)
    }
    
    func changeVarity(name: String) {
        let vcs = self.childViewControllers
        for vc in vcs {
            if let buyorsell = vc as? BuyViewController {
                buyorsell.moneyType = name
            }
        }
        self.leftBtn.setTitle("  \(name)", for: .normal)
    }
    
    ///处理红点
    func unReadDot() {
        if AppInfo.default.isLogin {
            self.redDot?.isHidden =  !self.viewModel.isNewMessage
        }
    }
    
    var isPresent: Bool = false
}

extension CurrencyTradeViewController: UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {
    
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.25
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        if self.isPresent {
            guard let toVc = transitionContext.viewController(forKey: .to)  else {
                return
            }
            transitionContext.containerView.addSubview(toVc.view)
            if let silderVC = toVc as? SliderViewController {
                silderVC.view.alpha = 0.0
                silderVC.contentView.x = -silderVC.contentView.width
                UIView.animate(withDuration: 0.25, animations: {
                    silderVC.contentView.x = 0
                    silderVC.view.alpha = 1.0
                }) { (_) in
                    transitionContext.completeTransition(true)
                }
            }
            
        }else {
            guard let fromVc = transitionContext.viewController(forKey: .from) else {
                return
            }
            transitionContext.containerView.addSubview(fromVc.view)
            if let silderVC = fromVc as? SliderViewController {
                silderVC.contentView.x = 0
                silderVC.view.alpha = 1.0
                UIView.animate(withDuration: 0.25, animations: {
                    silderVC.contentView.x = -silderVC.contentView.width
                    silderVC.view.alpha = 0.0
                }) { (_) in
                    transitionContext.completeTransition(true)
                }
            }
        }
    }
    
    public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresent = true
        return self
    }
    public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresent = false
        return self
    }
}
